﻿using System;
using System.Collections.Generic;
using System.Linq;
using Coleotrack.Core;
using Coleotrack.Data;
using Coleotrack.Service.Contracts;
using NHibernate;
using NHibernate.Linq;

namespace Coleotrack.Service
{
    public class UserService : ServiceBase<User>, IUserService
    {
        public UserService(INHibernateUnitOfWork unitOfWork) : base(unitOfWork)
        {
        }

        public override void Delete(User entity)
        {
            if (entity.Profile != null)
            {
                UnitOfWork.CurrentSession.Delete(entity.Profile);
            }

            base.Delete(entity);
        }

        public User GetByEmail(string email)
        {
            return this.Select().Single(u => u.Email.Equals(email));
        }

        public User GetByName(string name)
        {
            return this.Select().Single(u => u.Name.Equals(name));
        }

        public User GetByNameOrEmail(string nameOrEmail)
        {
            return this.Select().SingleOrDefault(u => u.Name.Equals(nameOrEmail) || u.Email.Equals(nameOrEmail));
        }

        public IEnumerable<Role> GetAllRoles()
        {
            return UnitOfWork.CurrentSession.Query<Role>().ToList();
        }

        public IEnumerable<User> AllActive()
        {
            return Select().Where(x => x.Active);
        }

        public bool Login(string name, string passwordHash)
        {
            return this.Select().Any(u => (u.Name.Equals(name) || u.Email.Equals(name)) && u.Password.Equals(passwordHash) && u.Active);
        }
    }
}